package com.rpp.study.controller;

import com.rpp.study.base.LagouResponse;
import com.rpp.study.feign.FeignCode;
import com.rpp.study.feign.FeignEmail;
import com.rpp.study.service.ICodeService;
import com.rpp.study.utils.RandomStringGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

/**
 * @Description
 * @Author rpp
 * @Date 2020/8/28 10:50 下午
 */
@RestController
@RequestMapping(value = "/api/code")
public class CodeController implements FeignCode {

    @Autowired
    FeignEmail feignEmail;

    @Autowired
    ICodeService codeService;

    /**
     * ⽣成验证码并发送到对应邮箱，成功true，失败 false
     *
     * @param email
     * @return
     */
    @Override
    @GetMapping(value = "/create/{email}")
    public LagouResponse<Boolean> create(@PathVariable("email") String email) {

        if (StringUtils.isBlank(email)) {
            return LagouResponse.error(false, "邮箱不能为空");
        }
        String code = RandomStringGenerator.getRandomString(6);
        //保存邮箱及对应验证码
        codeService.save(email, code);
        //调用邮箱服务发送邮件
        LagouResponse<Boolean> result = feignEmail.sendEmail(email, code);
        return result;
    }

    /**
     * 校验验证码是否正确，0正确1错误2超时
     *
     * @param email
     * @param code
     * @return
     */
    @Override
    @GetMapping(value = "/validate/{email}/{code}")
    public LagouResponse<Integer> validate(@PathVariable("email") String email,
                                           @PathVariable("code") String code) {
        if (StringUtils.isBlank(email)) {
            return LagouResponse.error(1, "邮箱不能为空");
        }
        if (StringUtils.isBlank(code)) {
            return LagouResponse.error(1, "验证码不能为空");
        }
        Integer validate = codeService.validate(email, code);
        if (validate == 1) {
            return LagouResponse.error(1, "验证码不存在");
        }
        if (validate == 2) {
            return LagouResponse.error(1, "验证码已过期");
        }
        return LagouResponse.success(0);
    }
}
